package com.ai.auth.service.impl;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ai.auth.entity.User;
import com.ai.auth.service.UserService;
import com.ai.core.dao.impl.BaseDaoImpl;
import com.ai.core.pagemode.PageFilter;
import com.alibaba.fastjson.JSONObject;


@Service("UserService")
public class UserServiceImpl implements UserService {

	@Autowired
	private BaseDaoImpl<User> userDao;
	 
	@Autowired
	private HttpServletRequest request;
	
	
	public User login(Map param) throws  IOException {
		String loginname = (String)param.get("loginname");
		String password = (String)param.get("password");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("loginname", loginname);
		params.put("password", password);
		User t = userDao.get("from User t where t.loginname = :loginname and t.password = :password", params);
		 
		return t;
	}
	
	public void save(Map param) throws  IOException {
		JSONObject userJO = (JSONObject)param.get("user"); 
		User user =JSONObject.parseObject(userJO.toJSONString(), User.class);
		userDao.save(user);
	}

	public List<User> find(Map param) throws  IOException { 
		JSONObject userJO = (JSONObject)param.get("user"); 
		User user =JSONObject.parseObject(userJO.toJSONString(), User.class);
		Map<String, Object> params = new HashMap<String, Object>();
		String hql = " from Tuser t ";
		List<User> l = userDao.find(hql + whereHql(user, params) , params);
		return l; 
	}
	
	
	private String whereHql(User user, Map<String, Object> params) {
		String hql = "";
		if (user != null) {
			hql += " where 1=1 ";
			if (user.getName() != null) {
				hql += " and t.loginname like :name";
				params.put("name", "%%" + user.getName() + "%%");
			}
			 
		}
		return hql;
	}

	private String orderHql(PageFilter ph) {
		String orderString = "";
		if ((ph.getSort() != null) && (ph.getOrder() != null)) {
			orderString = " order by t." + ph.getSort() + " " + ph.getOrder();
		}
		return orderString;
	}
}
